package demo;

public class ClassPractice {
    static class ListNode {
        private int val;
        private ListNode next;
        private ListNode(int val) {
            this.val = val;
        }
        public int getVal() {
            return val;
        }
    }

    public ListNode head;

    //输⼊两个链表，找出它们的第⼀个公共结点。
    public ListNode getIntersectionNode(ListNode headA,ListNode headB) {
        ListNode pl = headA;
        ListNode ps = headB;
        int len1 = 0;
        int len2 = 0;
        ListNode curA = headA;
        ListNode curB = headB;
        while (curA != null) {
            len1++;
            curA = curA.next;
        }
        while (curB != null) {
            len2++;
            curB = curB.next;
        }
        int len = len2 - len1;
        if (len < 0) {
            pl = headB;
            ps = headA;
            len = len2 - len1;
        }
        while (len != 0) {
            pl = pl.next;
            len--;
        }
        while (ps != pl) {
            ps = ps.next;
            pl = pl.next;
        }
        if (pl == null){
            return null;
        }
        return pl;
    }

    //拿到倒数第K个 节点的值
    public int kthToLast(int k) {
        if (k < 0) {
            return -1;
        }
        ListNode fast = head;
        ListNode slow = head;
        int count = k - 1;
        while (count != 0) {
            fast = fast.next;
            if (fast == null) {
                return -1;
            }
            count--;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow.val;
    }

    //取中间节点
    public ListNode middleNode(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null ) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}
